if exists (select 1
          from sysobjects
          where  id = object_id('bd_proc_overTimeResult')
          and type in ('P','PC'))
   drop procedure bd_proc_overTimeResult
go


create procedure bd_proc_overTimeResult (@order_id numeric) as
BEGIN
	DECLARE @user_serial bigint --
	DECLARE @returnRemark varchar(max) = '' --若单子被拒绝，这个是拒绝原因（多人拒绝，这里是全部人的）
	DECLARE @operator bigint --操作人，是加班申请单中的最后审批人
	DECLARE @beginDate DATE
	--获取驳回原因
	select @returnRemark = (SELECT
			'('+remark +')'
		FROM
			bd_kq_approvalRecord
		WHERE
			order_id = @order_id
			AND approve_key LIKE 'work%'
			AND approve_order NOT IN ( 0, 9999 )
			AND status = 0
		FOR XML PATH(''))
	--更新单子的取消/驳回原因
	update bd_over_time_order
		set return_remark = @returnRemark
		where order_id = @order_id

	--获取操作人
	select @operator = examine_user from bd_over_time_order where order_id = @order_id;

	--假期重新计算(这里不去关心申请的加班类型)
	DECLARE cursor_user CURSOR LOCAL FOR
		select  l.user_serial,o.ot_date
			from lr_jiaba l
			INNER JOIN bd_over_time_order o on l.order_id = o.order_id
			where l.order_id = @order_id and l.is_delete = 0

		OPEN cursor_user FETCH NEXT FROM cursor_user INTO @user_serial,@beginDate

		--提取第一条数据存放在变量中
		WHILE @@fetch_status = 0
					BEGIN
							--执行重新计算
							EXEC bd_proc_reset_data @beginDate,1,@user_serial,@operator

						FETCH NEXT FROM cursor_user INTO  @user_serial,@beginDate
					END


	--调用考勤重新计算

	DECLARE @users VARCHAR(MAX) = ''
	DECLARE @overTimeDate DATE

	SELECT
		@users = @users + CAST(u.user_serial AS VARCHAR(100)) + ','
	FROM (
			select DISTINCT user_serial from lr_jiaba where order_id = @order_id
	) u

	SET @users = SUBSTRING(@users,0, LEN(@users))
	SELECT @overTimeDate = ot_date from bd_over_time_order where order_id = @order_id
	EXEC bd_proc_timecard @overTimeDate,@users,5
END
go
